package com.gwt.tirso.gymkhana.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwt.tirso.gymkhana.shared.DelistedException;
import com.gwt.tirso.gymkhana.shared.FieldVerifier;
import com.gwt.tirso.gymkhana.shared.IdGenerator;

public class RegistrationStep1 implements EntryPoint{
	
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel emailPanel = new HorizontalPanel();
	private HorizontalPanel buttonsPanel = new HorizontalPanel();
	private Label name = new Label();
	private Label age = new Label();
	private Label email = new Label();
	private Label nick = new Label();
	private Label pass = new Label();
	private Label country = new Label();
	private Label city = new Label();
	private Label errorLabel = new Label();
	private Label errorEmailLabel = new Label("");
	private TextBox nameT = new TextBox();
	private TextBox ageT = new TextBox();
	private TextBox emailT = new TextBox();
	private TextBox nickT = new TextBox();
	private TextBox passT = new PasswordTextBox();
	private TextBox countryT = new TextBox();
	private TextBox cityT = new TextBox();
	private Button accept = new Button();
	private Button cancel = new Button();
	
	private Person pers =  new Person();
	private IRegistrationServiceAsync persCon;

	@Override
	public void onModuleLoad() {
		
		loadRegistrationStep1();
		
	}
	
    private void loadRegistrationStep1() {

		//Labels
		name.setText("Nombre");
		age.setText("Edad");
		email.setText("Email");
		nick.setText("Nick");
		pass.setText("Contraseña");
		country.setText("País");
		city.setText("Ciudad");
		
		emailPanel.add(emailT);
		emailPanel.add(errorEmailLabel);
		
		//textBoxes, writing areas
		nameT.setMaxLength(25);
		nameT.setVisibleLength(25);
		ageT.setMaxLength(3);
		ageT.setVisibleLength(3);
		emailT.setMaxLength(40);
		emailT.setVisibleLength(40);
		nickT.setMaxLength(15);
		nickT.setVisibleLength(15);
		passT.setMaxLength(8);
		passT.setVisibleLength(8);
		countryT.setMaxLength(15);
		countryT.setVisibleLength(15);
		cityT.setMaxLength(15);
		cityT.setVisibleLength(15);
		
		//VerticalPanel: adding elements
		mainPanel.add(name);
		mainPanel.add(nameT);
		mainPanel.add(age);
		mainPanel.add(ageT);
		mainPanel.add(email);
		mainPanel.add(emailPanel);
		mainPanel.add(nick);
		mainPanel.add(nickT);
		mainPanel.add(pass);
		mainPanel.add(passT);
		mainPanel.add(country);
		mainPanel.add(countryT);
		mainPanel.add(city);
		mainPanel.add(cityT);
		
		//buttons
		accept.setText("Aceptar");
		cancel.setText("Cancelar");
		buttonsPanel.add(accept);
		buttonsPanel.add(cancel);
		
		mainPanel.add(buttonsPanel);
		
		emailT.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				String s = emailT.getText();
				persCon = ConnectionRpc.initRpcRegistration();
				
				AsyncCallback<String> callback = new AsyncCallback<String>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(String result) {
						if(result == null){
							errorEmailLabel.setText(" E-mail disponible");
							errorEmailLabel.setStyleName("successLabel");
						}else{
							errorEmailLabel.setText(" El e-mail "+ result +" ya existe");
							errorEmailLabel.setStyleName("errorLabel");
						}		
					}
				};
				
				persCon.checkEmail(s, callback);
				
			}
		});
		
		accept.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				pers = receiveInfo();
				if(pers != null){
					acceptPerson(pers);
				}else{
					mainPanel.add(errorLabel);
				}
				
			}
		});
		
		cancel.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				cancelStep();
			}
		});
		
		mainPanel.addStyleName("registrationNext");
		RootPanel.get("registration").add(mainPanel);
		
	}

	protected void acceptPerson(Person pers2) {
    	persCon = ConnectionRpc.initRpcRegistration();
    	
		AsyncCallback<Person> callback = new AsyncCallback<Person>() {

			@Override
			public void onFailure(Throwable caught) {
				String details = caught.getMessage();
		        if (caught instanceof DelistedException) {
		          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
		        }

		        errorLabel.setText("Error: " + details);
		        errorLabel.setVisible(true);
			}

			@Override
			public void onSuccess(Person result) {
				inicStep();				
			}
		};
		//we call to the method "register user" here
		persCon.registerUser(pers, callback);
		
	}

	public Person receiveInfo(){
    	
    	//sending dates to other window and check all of them
    	String nameToList = nameT.getText();
		if (!FieldVerifier.isValidName(nameToList)) {
			errorLabel.setText("Escriba un nombre");
			return null;
		}
    	String ageToList = ageT.getText();
    	if (!FieldVerifier.isValidAge(ageToList)) {
			errorLabel.setText("Escriba su edad en notación numérica");
			return null;
		}
    	String emailToList = emailT.getText();
    	if (!FieldVerifier.isValidName(emailToList)) {
			errorLabel.setText("Ya existe un usuario registrado con ese email");
			return null;
		}
    	String nickToList = nickT.getText();
    	if (!FieldVerifier.isValidName(nickToList)) {
			errorLabel.setText("El nick escrito ya existe");
			return null;
		}
    	//Insert password: special treatment with jBCrypt
    	String passToList = passT.getText();
    	if (!FieldVerifier.isValidName(passToList)) {
			errorLabel.setText("Escriba una contraseña");
			return null;
		}
    	
    	
    	String countryToList = countryT.getText();
    	if (!FieldVerifier.isValidName(countryToList)) {
			errorLabel.setText("Escriba su país de residencia");
			return null;
		}
    	String cityToList = cityT.getText();
    	if (!FieldVerifier.isValidName(cityToList)) {
			errorLabel.setText("Escriba su ciudad de residencia");
			return null;
		}
    	
    	//create person object with all the information    	
    	Person p = new Person();
    	
    	p.setName(nameToList);
    	p.setAge(Integer.parseInt(ageToList));
    	p.setEmail(emailToList);
    	p.setNick(nickToList);
    	p.setPassword(passToList);
    	p.setCountry(countryToList);
    	p.setCity(cityToList);
    	
    	
    	
    	/*person id, with idgenerator
    	String key = IdGenerator.getInstance().getKey();
    	p.setId(key);*/
    	
    	
    	return p;
    	
    }
	private void inicStep(){
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		Window.alert("Registrado correctamente");
		RootPanel.get("registration").remove(mainPanel);
	}
	
	private void cancelStep(){
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("registration").remove(mainPanel);
	}

}
